<?php
namespace app\api\model;

use app\conmon\wxpay;
use think\Db;
use think\Cache;
class OrderModel  
{
    /**
     * 单例模式
     * @return OrderModel
     *
     */
    public static function instance(){
        static $m = null;
        if(!$m){
            $m = new OrderModel();
        }
        return $m;
    }
   /**
    * 检查商品
    */
    public function detail($goodsid,$field){
        
        $list = Db::name('goods')->field($field)->where(['goodsid'=>$goodsid,'integral'=>0])->find();
        return $list;
    }
    /**
     * 立即购买订单处理
     */
    
  public function goodsOrder($order,$goods,$uid){

        $open_rule = $goods['open_rule'];
        unset($goods['open_rule']);
        // 启动事务
        Db::startTrans();
        $time = time();
        //添加订单
        $order['uid'] = $uid;
        $order['createtime'] = $time;

        $orderid =  Db::name('goodsOrder')->insertGetId($order);

        //添加订单商品信息
        $goods['createtime'] = $time;
        $goods['uid'] = $uid;
        $goods['orderid'] = $orderid;
        $orderGoods = Db::name('orderGoods')->insert($goods);
        //库存处理

        if($open_rule == 1){
            $map['rule'] = $goods['rule'];
            if(!empty($goods['rule1'])) $map['rule1'] = $goods['rule1'];
            if(!empty($goods['rule2'])) $map['rule2'] = $goods['rule2'];
            $goodsstock = Db::name('goodsAttr')->where($map)->setDec('stock',$goods['num']);
            //$goodssales = Db::name('goodsAttr')->where($map)->setInc('sales',$goods['num']);
        }else{
            $goodsstock = Db::name('goods')->where('goodsid',$goods['goodsid'])->setDec('stock',$goods['num']);
            //$goodssales = Db::name('goods')->where('goodsid',$goods['goodsid'])->setInc('sales',$goods['num']);
        }
        if(!$orderid || !$orderGoods || !$goodsstock){
            // 回滚事务
            Db::rollback();
            return false;
        }
        // 提交事务
        Db::commit();
        return ['order_no'=>$order['order_no']];

    }
    /**
     * 购物车购买订单处理
     */
    public function cartsOrder($cart_data,$order_remark,$uid = 0){

        $cart_data = array_filter($cart_data);
        if(empty($cart_data) || !is_array($cart_data) || $uid<=0) return [false,1001,''];

        $cart_list = Db::name('cart')->field('cartid,bid,goodsid,price,rule,rule1,rule2,num')->select($cart_data['cartid']);

        if(empty($cart_list)) return [false,2002,''];

        foreach($cart_list as $value){
            $buss[$value['bid']][] =  $value;
        }
        Db::startTrans();
        foreach ($buss as $k=>$v){
            $total = $num = 0;
            foreach ($v as $val){


                //检测商品信息
                $goods = Db::name('goods')->field('name,bid,status,open_rule,stock,sales,min_price,template,weight,freight_count,freight_unify')->where('goodsid',$val['goodsid'])->find();

                if(empty($goods)) return [false,2006,''];  //未查找到商品信息
                if($goods['status'] == 0) return [false,2007,$goods['name']]; //商品已经下架
                //检测商品 库存

                if($goods['open_rule']==0){
                    $stock = [
                        'stock' => $goods['stock'],
                        'sales' => $goods['sales'],
                        'attrid' => 0,
                    ];
                }else{
                    $stock = Db::name('goodsAttr')->field('stock,sales,price,attrid')
                        ->where(['goodsid'=>$val['goodsid'],'rule'=>$val['rule'],'rule1'=>$val['rule1'],'rule2'=>$val['rule2']])->find();
                }
               

                if(empty($stock) || $stock['stock']<=$val['num']) return [false,2001,'商品：'.$goods['name'].';规则:'.$val['rule'].' '.$val['rule1'] . ' ' . $val['rule2']]; //库存不足 或不存在此商品规格
                //订单商品信息
                $orderGoods[] = [
                    'goodsid' => intval($val['goodsid']),
                    'num' => intval($val['num']),
                    'rule' => htmlspecialchars($val['rule']),
                    'rule1' => htmlspecialchars($val['rule1']),
                    'rule2' => htmlspecialchars($val['rule2']),
                    'price' => htmlspecialchars($val['price']),
                    'total_price' => $val['price']*intval($val['num']),
                    'uid' => $uid,
                    'attrid' => $stock['attrid'],
                    'createtime' => time()
                ];

                $total += $val['price']*$val['num']; //计算订单总价格

                $num += $val['num']; //计算订单总数量

            }
            //邮费
          

            //查询地址
            $address = AddressModel::instance()->defaultaddr($uid,$goods['bid']);
            //处理订单信息
	if(!$address){
                return [false,3002,''];
            }
            $order = [
                'order_no' => trade_no(),  // 订单号
                'bid' => $goods['bid'],
                'name' => $address['name'],
                'phone' => $address['phone'],
                'address' => $address['province'] . '-' . $address['city'] . '-' . $address['area'] .'-'. $address['address'],
                'num' => intval($num),
                'money' => $total,
                'remark' => !empty($order_remark)?htmlspecialchars($order_remark):'',
                'uid' => $uid,
                'createtime' => time()
            ];

            //创建订单
            $orderid = Db::name('goodsOrder')->insertGetId($order);

            if(!$orderid) {
                Db::rollback(); // 回滚事务
                return [false,2002,''];
            }


            //库存处理
            foreach($orderGoods as &$va){
                $open_rule = Db::name('goods')->field('open_rule')->where('goodsid',$va['goodsid'])->find();

                if($open_rule['open_rule'] == 1){
                    $map['rule'] = $goods['rule'];
                    if(!empty($goods['rule1'])) $map['rule1'] = $goods['rule1'];
                    if(!empty($goods['rule2'])) $map['rule2'] = $goods['rule2'];
                    $goodsstock = Db::name('goodsAttr')->where($map)->setDec('stock',$goods['num']);
                    //$goodssales = Db::name('goodsAttr')->where($map)->setInc('sales',$goods['num']);
                }else{

                    $goodsstock = Db::name('goods')->where('goodsid',$va['goodsid'])->setDec('stock',$va['num']);
                    //$goodssales = Db::name('goods')->where('goodsid',$va['goodsid'])->setInc('sales',$va['num']);
                }

                //删除购物车

                $map['uid'] = $uid;
                Db::name('cart')->where($map)->delete($cart_data['cartid']);

                if(!$goodsstock){
                    // 回滚事务
                    Db::rollback();
                    return false;
                }

            }

            foreach ($orderGoods as &$val){
                $val['orderid'] = $orderid;
            }

            //订单商品信息添加
            $orderg = Db::name('orderGoods')->insertAll($orderGoods);
            if(!$orderg){
                Db::rollback();
                return false;
            }

            $ordernos[] = $order['order_no'];


        }
        //print_r($orderGoods);exit;

        //判断订单个数  大于1生成临时订单号
        if(count($ordernos)>1){
            $ordernoData = [
                'out_trade_no' => 'o'.trade_no(),  // 订单编号
                'order_no' => implode(',',$ordernos),  // 订单号
                'uid' => $uid
            ];

            $ordernoRes = Db::name('orderNo')->insert($ordernoData);
            if(!$ordernoRes){
                Db::rollback(); // 回滚事务
                return [false,2002,''];
            }
            $orderResult = ['order_no'=>$ordernoData['out_trade_no']];
        }else{
            $orderResult = ['order_no'=>$order['order_no']];
        }
        //提交事务
        Db::commit();
        return [true,'',$orderResult];

    }
/**
     * 获取订单支付参数
     */
    public function getOrderPayParams($order_no,$title,$uid){
        $weixin_url = "https://shop.zijunxcx.cn/api/Paynotify/wxgoodsnotify";   //微信回调地址
        $field = 'orderid,order_no,status,pay_way,money,createtime,wxpayparms';
        $openid = Db::name('user')->field('uid,openid')->where('uid',$uid)->find();
        $money = 0;  //支付总金额
        $where = [
            'order_no' => $order_no,
            'uid' => $uid,
            'status' => 1
        ];
        $order = Db::name('goodsOrder')->field($field)->where($where)->find();
        if(!empty($order)) {
            $money = $order['money'];
        }else{
            return false;
        }
        $payment_money = $money * 100;
        //获取支付参数
        $wx_pay = new wxpay();

        $res_weixin = $wx_pay->getAppData($order_no, $payment_money, $title, $weixin_url,$openid['openid'],$setAttach='');
        $params['weixin'] = $res_weixin ? $res_weixin : (object)null;
        return $params;
    }
/**
     * 取消订单
     */
    public function delOrder($orderid, $uid){
        if(empty($orderid) || empty($uid)) return false;
        Db::startTrans();
        //取消订单
        $gdResult = Db::name('goodsOrder')->where(['orderid'=>$orderid,'uid'=>$uid])->update(['status'=>-1,'take_time'=>time()]);
        $orderGoods = Db::name('orderGoods')->field('goodsid,rule,rule1,rule2,num')->where(['orderid' => $orderid])->select();
        foreach ($orderGoods as $val){
            $mapSt['goodsid'] = $val['goodsid'];
            if($val['rule'] || $val['rule1'] || $val['rule2']){
                isset($val['rule']) ? $mapSt['rule'] = $val['rule'] : $mapSt['rule'] = '';
                isset($val['rule1']) ? $mapSt['rule1'] = $val['rule1'] : $mapSt['rule1'] = '';
                isset($val['rule2']) ? $mapSt['rule2'] = $val['rule2'] : $mapSt['rule2'] = '';
                //$stock = Db::name('goodsAttr')->where($mapSt)->setDec('sales',$val['num']);
                $stock1 = Db::name('goodsAttr')->where($mapSt)->setInc('stock',$val['num']);
            }else{
                //$stock = Db::name('goods')->where($mapSt)->setDec('sales',$val['num']);
                $stock1 = Db::name('goods')->where($mapSt)->setInc('stock',$val['num']);
            }
            if (!$stock1) {
                break;
            }
        }
        if (!$gdResult || !$stock1) {
            Db::rollback(); //回滚事务
            return false;
        }

        Db::commit(); //提交事务
        return true;
    }
    /**
     * 我的订单
     */
    public function getOrderLists($type,$uid){
        $field = 'orderid,uid,order_no,bid,num,money,status,createtime,paytime,remark';
        if($type == 0){
            $order = Db::name('goodsOrder')->field($field)->where(['uid'=>$uid])->order('orderid desc')->select();
        }else{
            $order = Db::name('goodsOrder')->field($field)->where(['uid'=>$uid,'status'=>$type])->order('orderid desc')->select();
        }
        foreach ($order as $key=>&$val){
            $buss = Db::name('business')->field('bid,name,address,logo')->where('bid',$val['bid'])->find();
            $val['busname'] = $buss['name'];
            $val['logo'] = $buss['logo'];
            $val['busaddress'] = $buss['address'];
            $orderGoods = Db::name('orderGoods')->field('orderid,ogid,goodsid,price,total_price,num,rule,rule1,rule2')->where('orderid',$val['orderid'])->select();
            foreach ($orderGoods as &$v){
                $goods = Db::name('goods')->field('goodsid,pic,name,unit,explain,gain_integral,discount')->where('goodsid',$v['goodsid'])->find();
                $v['pic'] = uploadpath('goods',$goods['pic']);;
                $v['name'] = $goods['name'];
                $v['unit'] = $goods['unit'];
                $v['explain'] = $goods['explain'];
                $v['goodsid'] = $goods['goodsid'];
            }
            $val['goods'] =  $orderGoods;
        }
        return $order;

    }
/**
     * 订单详情
     */
    public function getOneOrder($order){
        $goodsOder = Db::name('goodsOrder')
            ->field('orderid,uid,order_no,num,money,status,name,phone,address,createtime,paytime,sendtime,taketime,remark')
            ->where('orderid',$order)
            ->find();
        $oderGoods = Db::name('orderGoods')
            ->alias('o')
            ->field('o.ogid,o.orderid,o.uid,o.goodsid,o.num,o.rule,o.rule1,o.rule2,o.price,o.total_price,u.nickname,g.pic,g.name,u.head')
            ->join('user u','u.uid = o.uid')
            ->join('goods g','g.goodsid = o.goodsid')
            ->where('o.orderid',$goodsOder['orderid'])
            ->select();
	foreach ($oderGoods as &$val){
            $val['pic'] = uploadpath('goods',$val['pic']);
        }
        $goodsOder['goods'] = $oderGoods;
        return $goodsOder;
        
    }
    /**
     * 确认收货
     */
    public function takeGoods($orderid,$uid){
        $status = Db::name('goodsOrder')->field('status,orderid,uid')->where(['uid'=>$uid,'orderid'=>$orderid])->find();
        if($status['status'] == 3){
            $result = Db::name('goodsOrder')->where(['uid'=>$uid,'orderid'=>$orderid])->update(['status'=>4]);
        }else{
            return [false,2008];
        }
        return [true,$result];
    }
    /**
     * 微信支付回调处理
     */
   public function wxNotify(){
        $data = $GLOBALS['HTTP_RAW_POST_DATA'];
        $weixin = new wxpay();
        $result = $weixin->verfy($data);
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($result['transaction_id']);
        $result = \WxPayApi::orderQuery($input);
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            $data = [
                'status' => 2, //修改订单状态    状态（1：待付款 2：待发货 3：待收货  4：已完成  -1：关闭）
                'paytime' => time(),
                'pay_user' => $result['openid'],
                'pay_serial_number' => $result['transaction_id'],
                'pay_way' => 'weixin'// alipay：支付宝  weixin:微信
            ];
            $this->changeOrder($result['out_trade_no'], $data);
        }
        return false;

    }
    /**
     * 改变订单状态 销量更新
     */
    public function changeOrder($orderid,$data){
        $order = Db::name('goodsOrder')->field('orderid,order_no,status')->where('order_no',$orderid)->find();
        if(empty($order))  return false;
        if($order['status'] == 1){
            Db::startTrans();
            //更新订单
            $result = Db::name('goodsOrder')->where('order_no',$orderid)->update($data);
            //销量
            $orderGoods=Db::name('orderGoods')->where(['orderid'=>$order['orderid']])->field('goodsid,num,rule,rule1')->select();
            foreach ($orderGoods as $val){
                $goods = Db::name('goods')->where('goodsid',$val['goodsid'])->setInc('sales', $val['num']);
            }
            if (!$result || !$goods) {
                Db::rollback(); //回滚事务
                return false;
            }
            //提交事务
            Db::commit();
            return $result;
        }else{
            return true;
        }
    }

/**
     * 充值
     */
    public function rechargePay($money,$uid,$order_no){
        $weixin_url = "https://shop.zijunxcx.cn/api/Paynotify/wxtopUpnotify";   //微信回调地址
        $openid = Db::name('user')->field('uid,openid,bid')->where('uid',$uid)->find();
        $payment_money = $money * 100;
        //获取支付参数
        $wx_pay = new wxpay();
        
        $res_weixin = $wx_pay->getAppData($order_no, $payment_money, '充值', $weixin_url,$openid['openid'],$setAttach='');
        $params['weixin'] = $res_weixin ? $res_weixin : (object)null;
        return $params;
    }
/**
     * 充值回调
     */
    public function topUpNotify(){
	
        $data = $GLOBALS['HTTP_RAW_POST_DATA'];
        $weixin = new wxpay();
        $result = $weixin->verfy($data);
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($result['transaction_id']);
        $result = \WxPayApi::orderQuery($input);
	
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            $goodsorde = Db::name('user')->field('uid,bid,openid')->where(['openid'=>$result['openid']])->find();
            $data = [
                'uid' => $goodsorde['uid'],
                'bid' => $goodsorde['bid'],
                'order_no' => $result['out_trade_no'],
                'money' => $result['total_fee'] / 100,
                'paytime' => time(),
                'pay_user' => $result['openid'],
                'pay_serial_number' => $result['transaction_id'],
                'pay_way' => 'weixin'// alipay：支付宝  weixin:微信
            ];
            $results = Db::name('topUp')->insert($data);
            $integral = 0;
            $integral = round($data['money'] * 0.2);
            if($results > 0){
             
                $usermoney = Db::name('user')->where('uid',$data['uid'])->setInc('money',$data['money']);
                $userin = Db::name('user')->where('uid',$data['uid'])->setInc('integral',$integral);
               
                echo 'SUCCESS';
            }
            return false;
        }
        return false;
    }
    /**
     * 余额/积分 支付
     */
    public function getorderPayIntegral($order_no,$type,$uid){
        $order = Db::name('goodsOrder')->field('orderid,order_no,status,bid,uid,money')->where('order_no',$order_no)->find();
        $getuser = Db::name('user')->field('money,integral,uid,bid')->where('uid',$order['uid'])->find();
        if($type == 1){
            $payway = 'balance';  //余额购买
            if($getuser['money'] < $order['money']){
                return [false,2010];
            }
        }elseif ($type == 2){
            $payway = 'integral';  //积分购买
            if($getuser['integral'] < $order['money']){
                return [false,2011];
            }
        }else{
            $payway = '';
        }
        $data = [
            'paytime' => time(),
            'pay_way' => $payway,
            'status'  => 2
        ];
        if(empty($order))  return [false,0];
        if($order['status'] == 1){
            Db::startTrans();
            //更新订单
            $result = Db::name('goodsOrder')->where('order_no',$order_no)->update($data);
            //销量
            $orderGoods=Db::name('orderGoods')->where(['orderid'=>$order['orderid']])->field('goodsid,num,rule,rule1')->select();
            foreach ($orderGoods as $val){
                $goods = Db::name('goods')->where('goodsid',$val['goodsid'])->setInc('sales', $val['num']);
            }
            if($type == 1){
                $bainpay = Db::name('user')->where('uid', $order['uid'])->setDec('money', $order['money']);
            }elseif ($type == 2){
                $bainpay = Db::name('user')->where('uid', $order['uid'])->setDec('integral', $order['money']);
            }
            if (!$result || !$goods || !$bainpay) {
                Db::rollback(); //回滚事务
                return [false,0];
            }
            //提交事务
            Db::commit();
            return [true,$result];
        }else{
            return [false,0];
        }

    }
/**
     * 充值记录
     */
    public function recharge($uid,$bid){
        $result=Db::name('topUp')->where(['uid'=>$uid,'bid'=>$bid])->field('order_no,topid,uid,bid,money,pay_user,pay_serial_number,paytime,pay_way')->select();
        foreach($result as $key =>&$vo){
        $vo['paytime']=date('Y-m-d',$vo['paytime']);
        }
        return $result;
    }

}
